﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using Newtonsoft.Json;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
namespace Che300
{
    public class CheCrawler
    {
        #region 获取汽车品牌信息
        //  public static string PinPaiInfo;
        //  public static   
        public static List<ChePinPai> GetPinPaiInfo()
        {
            //获取汽车品牌
            ArrayList PinPaiList = new ArrayList();
            var CheUrl = "https://www.che300.com/";
            BaseCrawler baseCrawler = new BaseCrawler();

            baseCrawler.OnCompleted += (s, e) =>
            {
                HtmlWeb htmlWeb = new HtmlWeb();
                HtmlDocument document = htmlWeb.Load(e.Uri);
                HtmlNodeCollection collection = document.DocumentNode.SelectNodes("//p[@class='pinpailist list_1']");
                if (collection != null)
                {

                    foreach (var item in collection)
                    {
                        Dictionary<string, string> dictionary = new Dictionary<string, string>();
                        string PinPaiID = item.Attributes["id"].Value;//品牌Id
                        string PinPaiName = item.InnerText;//品牌名称
                        dictionary.Add("PinPaiId", PinPaiID);
                        dictionary.Add("PinPaiName", PinPaiName);
                        PinPaiList.Add(dictionary);
                        // Console.WriteLine(PinPaiID);

                    }

                }
            };

            baseCrawler.Start(new Uri(CheUrl)).Wait();
            string jstr = JsonConvert.SerializeObject(PinPaiList);
            List<ChePinPai> list = JsonConvert.DeserializeObject<List<ChePinPai>>(jstr);
            return list;
        }
        #endregion
        #region 获取车系信息

        /// <summary>
        /// 获取车系信息
        /// </summary>
        /// <param name="PinPaiId">品牌Id</param>
        /// <returns>返回车系Json字符串</returns>
        public static string CarSeriesInfo;
        public static List<CheSeries> GetCarSeries(string PinPaiId)
        {
            //获取汽车品牌id  利用id拼接链接地址        
            //获取车系的请求链接：https://ssl-meta.che300.com/meta/series/series_brand1.json?v=159   
            var CarSeriesUrl = "https://ssl-meta.che300.com/meta/series/series_brand" + PinPaiId + ".json";
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                CarSeriesInfo = e.PageSource;
            };
            baseCrawler.Start(new Uri(CarSeriesUrl)).Wait();
            string jstr = Regex.Unescape(CarSeriesInfo);
            List<CheSeries> list = JsonConvert.DeserializeObject<List<CheSeries>>(jstr);
            return list;
        }
        #endregion
        #region 获取车型信息
        /// <summary>
        /// 获取车型
        /// </summary>
        /// <param name="SeriesId">车系Id</param>
        /// <returns>返回车型json字符串</returns>
        public static string CarModelInfo;
        public static List<CheModel> GetCarModel(string SeriesId)
        {
            var CarSeriesUrl = "https://ssl-meta.che300.com/meta/model/model_series" + SeriesId + ".json";
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                CarModelInfo = e.PageSource;
            };
            baseCrawler.Start(new Uri(CarSeriesUrl)).Wait();
            string jstr = Regex.Unescape(CarModelInfo);
            List<CheModel> list = JsonConvert.DeserializeObject<List<CheModel>>(jstr);
            return list;
        }
        #endregion
        #region 获取汽车报价
        /// <summary>
        /// 获取汽车报价
        /// </summary>
        /// <param name="provId">省市Id</param>
        /// <param name="cityId">城市Id</param>
        /// <param name="brandId">品牌Id</param>
        /// <param name="seriesId">车系Id</param>
        /// <param name="modelId">车型Id</param>
        /// <param name="regDate">日期 格式xxxx-xx</param>
        /// <param name="mile"></param>
        /// <returns>获取报价json字符串</returns>
        //public static string CarPrice;
        public static ChePrice GetCarPrice(string provId, string cityId, string brandId, string seriesId, string modelId, string regDate, string mile)
        {
            //var dingjiaUrl = " https://dingjia.che300.com/app/EvalResult/getPreSaleRate?prov=12&city=12&brand=1&series=5&model=1134332&regDate=2017-1&mile=2";
            var dingjiaUrl = "https://dingjia.che300.com/app/EvalResult/getPreSaleRate?prov=" + provId + "&city=" + cityId + "&brand=" + brandId + "&series=" + seriesId + "&model=" + modelId + "&regDate=" + regDate + "&mile" + mile;
            BaseCrawler baseCrawler = new BaseCrawler();
            ArrayList CarPriceS = new ArrayList();
            baseCrawler.OnCompleted += (s, e) =>
            {
                // CarPrice = e.PageSource;
                JObject jPrice = (JObject)JsonConvert.DeserializeObject(e.PageSource);
                string CarPrice = jPrice["success"].ToString();
                JArray jArray = (JArray)JsonConvert.DeserializeObject(CarPrice);
                foreach (var item in jArray)
                {
                    string price = item["price"].ToString();
                    CarPriceS.Add(price);
                }
            };
            baseCrawler.Start(new Uri(dingjiaUrl)).Wait();
            ChePrice chePrice = new ChePrice();
            chePrice.price = CarPriceS;

            return  chePrice;
        }
        #endregion
        #region 获取省市

        //https://dingjia.che300.com/api/lib/util/city/prov_with_city?callback=jQuery183014398943682875975_1524644792310&format=jsonp&_=1524644792535 省份Json
        public static string Prov;
        public static Provinces GetProv()//获取省
        {
            var ProvUrl = "https://dingjia.che300.com/api/lib/util/city/prov_with_city";
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                Prov = e.PageSource;
            };
            baseCrawler.Start(new Uri(ProvUrl)).Wait();
            string pjstr = Regex.Unescape(Prov);
            Provinces provinces = new Provinces();
            provinces.prov_city.Add(pjstr);
            return provinces;
        }
        //https://ssl-meta.che300.com/location/all_city.json 城市Json
        // public static string City;
        //public static string GetCity()//获取市
        //{
        //    var CityUrl = "https://ssl-meta.che300.com/location/all_city.json";
        //    BaseCrawler baseCrawler = new BaseCrawler();
        //    baseCrawler.OnCompleted += (s, e) =>
        //    {
        //        City = e.PageSource;
        //    };
        //    baseCrawler.Start(new Uri(CityUrl)).Wait();
        //    return Regex.Unescape(City);
        //}
        #endregion
    }
    public class HomeChe
    {
        #region 爬取二手车之家
        #region 获取品牌
        //https://www.che168.com/Handler/ScriptCarList_V1.ashx?needData=1

        public static string GetCheHomePinPai()
        {
            var PinPaiUrl = "https://www.che168.com/Handler/ScriptCarList_V1.ashx?needData=1";

            BaseCrawler baseCrawler = new BaseCrawler();
            ArrayList arrayid = new ArrayList();
            ArrayList arrayname = new ArrayList();
            Dictionary<object, object> dic = new Dictionary<object, object>();
            baseCrawler.OnCompleted += (s, e) =>
            {
                string Pinpai = e.PageSource;
                // Console.WriteLine(Pinpai);
                int One = Pinpai.IndexOf('3');
                string Pstr = Pinpai.Substring(One, Pinpai.Length - One - 2);
                string[] PPStr = Pstr.Split(',');
                for (int i = 0; i < PPStr.Count(); i++)
                {
                    // Console.WriteLine(PPStr[i]);
                    arrayid.Add(PPStr[i]);
                    i++;

                }
                for (int i = 1; i < PPStr.Count(); i++)
                {
                    // Console.WriteLine(PPStr[i]);
                    arrayname.Add(PPStr[i]);
                    i++;
                }
                for (int i = 0; i < arrayid.Count; i++)
                {
                    dic.Add(arrayid[i], arrayname[i]);
                }



            };
            baseCrawler.ErStart(new Uri(PinPaiUrl)).Wait();
            string Pjson = JsonConvert.SerializeObject(dic);
            //  Console.WriteLine(Pjson);
            return Pjson;
        }
        #endregion
        #region 获取车系
        /// <summary>
        /// 获取二手车之家车系
        /// </summary>
        /// <param name="bid">汽车品牌ID</param>
        /// <returns></returns>
        public static string GetCheHomeSeries(string bid)
        {
            var Url = "https://www.che168.com/Handler/ScriptCarList_V1.ashx?seriesGroupType=2&needData=2&bid=" + bid;
            ArrayList SeriesID = new ArrayList();
            ArrayList SeriesName = new ArrayList();
            Dictionary<object, object> SeriesDic = new Dictionary<object, object>();
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                string Data = e.PageSource;
                //  Console.WriteLine(SeriesData);
                int BeginIndex = Data.LastIndexOf("=") + 2;
                int OverIndex = Data.Length - BeginIndex - 2;
                string SeriesData = Data.Substring(BeginIndex, OverIndex);
                string[] SeriesInfo = SeriesData.Split(',');
                for (int i = 0; i < SeriesInfo.Length; i++)
                {
                    SeriesID.Add(SeriesInfo[i]);
                    //Console.WriteLine(SeriesInfo[i]);
                    i++;
                }
                for (int i = 1; i < SeriesInfo.Length; i++)
                {
                    SeriesName.Add(SeriesInfo[i]);
                    i++;
                }
                for (int i = 0; i < SeriesID.Count; i++)
                {
                    SeriesDic.Add(SeriesID[i], SeriesName[i]);
                }
            };
            baseCrawler.ErStart(new Uri(Url)).Wait();
            string SeriesJson = JsonConvert.SerializeObject(SeriesDic);
            return SeriesJson;
        }
        #endregion
        #region 获取车型
        public static string UsedCarInfo;
        public static string CarModel(string seriesidId)
        {
            var ModelUrl = "https://www.che168.com/Handler/ScriptCarList_V1.ashx?seriesGroupType=2&needData=3&seriesid=" + seriesidId;
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                UsedCarInfo = e.PageSource;
                //Console.WriteLine(e.PageSource);
            };
            baseCrawler.ErStart(new Uri(ModelUrl)).Wait();
            return UsedCarInfo;
        }
        #endregion
        #region 获取车价
        public static string PriceStr;
        /// <summary>
        /// 获取车价
        /// </summary>
        /// <param name="pid">省份id</param>
        /// <param name="cid">城市id</param>
        /// <param name="mileage">行驶里程  单位： 公里</param>
        /// <param name="time">首次上牌时间 格式：xxxx-xx</param>
        /// <param name="specid">车型Id</param>
        /// <returns></returns>
        public static string GetPrice(string pid, string cid, string mileage, string time, string specid)
        {
            // https://pinguapi.che168.com/v1/auto/usedcarassess.ashx?_appid=pc.pingu&_sign=&encoding=gb2312&pid=330000&cid=330100&mileage=4000&firstregtime=2018-02&specid=32644&iscondition=1&_appversion=2.04v&mark=uahp10004
            var url = "https://pinguapi.che168.com/v1/auto/usedcarassess.ashx?_appid=pc.pingu&_sign=&encoding=gb2312&pid=" + pid + "&cid=" + cid + "&mileage=" + mileage + "&firstregtime=" + time + "&specid=" + specid + "&iscondition=1&_appversion=2.04v&mark=uahp10004";
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                //  Console.WriteLine(e.PageSource);
                JObject Price = (JObject)JsonConvert.DeserializeObject(e.PageSource);
                //Console.WriteLine(Price);
                PriceStr = Price["result"].ToString();
                // Console.WriteLine(result);

            };
            baseCrawler.ErStart(new Uri(url)).Wait();
            return PriceStr;
        }
        #endregion
        #region 获取省市列表      
        public static string GetProvinces()
        {
            var url = "https://www.che168.com/pinggu/";
            BaseCrawler baseCrawler = new BaseCrawler();
            ArrayList list = new ArrayList();
            baseCrawler.OnCompleted += (s, e) =>
            {
                // Console.WriteLine(e.PageSource);
                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(e.PageSource);
                HtmlNodeCollection collection = document.DocumentNode.SelectNodes("//div[@class='city']/a");
                if (collection != null)
                {

                    foreach (var item in collection)
                    {
                        string PId = item.Attributes["pid"].Value;
                        // Console.WriteLine(PId);
                        string Pname = item.Attributes["pidName"].Value;
                        string Cid = item.Attributes["cid"].Value;
                        string Cname = item.InnerText;
                        //Console.WriteLine(Pname);
                        Dictionary<object, object> dictionary = new Dictionary<object, object>();
                        Dictionary<object, object> cdic = new Dictionary<object, object>();
                        dictionary.Add("PrvoinceId", PId);
                        dictionary.Add("ProvinceName", Pname);
                        cdic.Add("CityId", Cid);
                        cdic.Add("CityName", Cname);
                        dictionary.Add("data", cdic);
                        list.Add(dictionary);
                    }

                }
            };
            baseCrawler.ErStart(new Uri(url)).Wait();
            return JsonConvert.SerializeObject(list);
        }
        #endregion
        #endregion
    }
    #region 汽车品牌类
    /// <summary>
    /// 汽车品牌
    /// </summary>
    public class ChePinPai
    {
        public int PinPaiId { get; set; }
        public string PinPaiName { get; set; }
    }
    #endregion
    #region 汽车车系类
    /// <summary>
    /// 汽车车系
    /// </summary>
    public class CheSeries
    {
        public int series_id { get; set; }
        public string series_name { get; set; }
        /// <summary>
        /// 是否是新能源
        /// </summary>
        public string is_green { get; set; }
        /// <summary>
        /// 车系分组
        /// </summary>
        public string series_group_name { get; set; }
    }
    #endregion
    #region 汽车车型类
    /// <summary>
    /// 汽车车型
    /// </summary>
    public class CheModel
    {
        public string model_id { get; set; }
        public string model_name { get; set; }
        public string model_price { get; set; }
        public string model_year { get; set; }
        /// <summary>
        /// 最早上牌年份
        /// </summary>
        public string min_reg_year { get; set; }
        /// <summary>
        /// 最晚上牌年份
        /// </summary>
        public string max_reg_year { get; set; }
        /// <summary>
        /// 排量
        /// </summary>
        public string liter { get; set; }
        public string liter_type { get; set; }
        public string gear_type { get; set; }
        public string discharge_standard { get; set; }
        public string is_green { get; set; }

    }
    #endregion
    #region 汽车估价类
    public class ChePrice
    {
        public ArrayList price { get; set; }
        //public string price1 { get; set; }
        //public string price2 { get; set; }
        //public string price3 { get; set; }
        //public string price4 { get; set; }
        //public string price5 { get; set; }
        //public string price6 { get; set; }
        //public string price7 { get; set; }
      
    }
    #endregion
    #region 省市
    public class Provinces
    {
        public ArrayList prov_city { get; set; }
    }
    #endregion
}
